package com.pad.filelibrary.utils;

import android.content.Context;
import android.util.Log;

import com.pad.filelibrary.interfacedir.ZipResultListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
 * @anthor Mr.Zan
 * @email  644962006@qq.com
 * @time 2025/2/28 11:12
 * @describe  Zip文件工具类
 */
public class ZipUtils {

    /**
     * 压缩文件
     *
     * @param folderString
     * @param fileString
     * @param zipOutputSteam
     * @throws Exception
     */
    private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
        if (zipOutputSteam == null)
            return;
        FileInputStream inputStream = null;
        try {
            File file = new File(folderString + fileString);
            if (file.isFile()) {
                ZipEntry zipEntry = new ZipEntry(fileString);
                inputStream = new FileInputStream(file);
                zipOutputSteam.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[4096];
                while ((len = inputStream.read(buffer)) != -1) {
                    zipOutputSteam.write(buffer, 0, len);
                }
                zipOutputSteam.closeEntry();
            } else {
                //文件夹
                //无论有没有子文件，都进行文件夹的创建
                ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
                zipOutputSteam.putNextEntry(zipEntry);
                zipOutputSteam.closeEntry();
                String[] childFileList = file.list();
                //没有子文件和压缩
                //子文件和递归
                if (childFileList != null) {
                    for (int i = 0; i < childFileList.length; i++) {
                        File cacheFile = new File(childFileList[i]);
                        String folderResult = folderString;
                        ZipFiles(folderResult, fileString + File.separator + cacheFile.getName(), zipOutputSteam);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    // 递归删除目录及其子目录和文件
    public static boolean deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        boolean delete = file.delete();
                        if (!delete){
                            Log.e("++ Mr.Zan ++", "deleteDirectory: 删除失败"+file.getAbsolutePath());
                        }else {
                            Log.e("++ Mr.Zan ++", "deleteDirectory: 删除成功"+file.getName());
                        }
                    }
                }
            }
        }
        return directory.delete();
    }

    private static void unZipChild(ZipFile zipFile, ZipEntry zipEntry, String targetFolder) {
        try {
            if (zipEntry.isDirectory()) {
                String targetDir = targetFolder + zipEntry.getName();
                new File(targetDir).mkdirs();
            } else {
                InputStream inputStream = zipFile.getInputStream(zipEntry);
                FileOutputStream outputStream = new FileOutputStream(new File(targetFolder, zipEntry.getName()));
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.close();
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //解压------------------------------------------------------------------------------------

    /**
     * @param zipFileName  压缩文件路径
     * @param targetFolder 解压出来的路径
     */
    public static void unZip(String zipFileName, String targetFolder) {
        try {
            deleteDirectory(new File(targetFolder));
            File targetFile = new File(targetFolder);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            ZipFile zipFile = new ZipFile(zipFileName);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();
                // 在这里可以对每个条目进行操作
                unZipChild(zipFile, zipEntry, targetFolder);
            }
            zipFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    //压缩------------------------------------------------------------------------------------

    /**
     * 压缩文件和文件夹
     *
     * @param srcFileString 要压缩的文件或文件夹
     * @param zipFileString 压缩完成的Zip路径
     * @throws Exception
     */
    public static boolean ZipFolder(String srcFileString, String zipFileString, String zipName, ZipResultListener listener) {
        //创建ZIP
        ZipOutputStream outZip = null;
        File file = null;
        try {
            //创建文件
             file = new File(srcFileString);
            File outPath = new File(zipFileString);
            if (!outPath.exists()) {
                outPath.mkdirs();
            }
            outZip = new ZipOutputStream(new FileOutputStream(new File(outPath, zipName)));
            //压缩
            ZipFiles(file.getParent() + File.separator, file.getName(), outZip);


        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            //完成和关闭
            if (outZip != null) {
                try {
                    outZip.flush();
                    outZip.finish();
                    outZip.close();
                    if (listener != null){
                        listener.isZipSuccess(true);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }

    }

    /**
     * 文件移动
     * @param context
     * @param sourcePath
     * @param destFolderName
     */
    public void moveFileToInternalStorage(Context context, String sourcePath, String destFolderName) {
        File sourceFile = new File(sourcePath);
        File destDir = context.getDir(destFolderName, Context.MODE_PRIVATE);
        File destFile = new File(destDir, sourceFile.getName());

        try {
            // 复制文件到新位置
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            fis.close();
            fos.close();

            // 删除原始文件（如果需要）
            sourceFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


